<template>
	<div class="source-list">
		<el-row type="flex" justify="space-between" align="middle" class="screend">
				<div>
					<el-radio-group v-model="queryInfo.collect" size="small" @change="collectChanged">
						<el-radio-button :label="false">全部</el-radio-button>
						<el-radio-button :label="true">收藏</el-radio-button>
					</el-radio-group>
				</div>
				<div v-if="isShowAdd">
					<el-button type="success" size="mini" @click="uploadDialogVisible = true">添加素材</el-button>
				</div>
			</el-row>

			<!-- 图片视图 -->
			<el-row :gutter="15">
				<el-col :sm="8" :md="4" v-for="(item, i) in imagesSource" :key="i">
					<div class="img-box" @click="selected = i">
						<el-image :src="item.url" fit="cover">
						</el-image>
						<!-- 选项 -->
						<div class="img-option" v-if="isShowOption">
							<el-tooltip effect="dark" content="收藏" placement="top" :enterable="false">
								 <el-button
									:class="['collect-btn', item.is_collected ? 'on' : '']"
									:icon="item.is_collected ? 'el-icon-star-on' : 'el-icon-star-off'"
									size="mini"
									:loading="item.option"
									@click="updateCollect(item)"></el-button>
							</el-tooltip>
							<el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
								<el-button
									class="collect-btn"
									icon="el-icon-delete"
									size="mini"
									:loading="item.option"
									@click="_deleteImage(item)"></el-button>
							</el-tooltip>
						</div>
						<!-- 选中状态 -->
						<div class="selected" v-if="selected === i && isShowSelected"></div>
					</div>
				</el-col>
			</el-row>

			<!-- 分页器 -->
			<el-pagination background :current-page="queryInfo.page" :page-size="queryInfo.per_page" :total="total" layout="prev, pager, next"
			 @current-change="handleCurrentChange">
			</el-pagination>

		<!-- 上传素材对话框 -->
		<el-dialog title="上传素材" :visible.sync="uploadDialogVisible" width="50%">
			<el-upload v-if="uploadDialogVisible" drag action="http://api-toutiao-web.itheima.net/app/v1_0/user/images" :headers="uploadHeaders"
			 name="image" multiple :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadError">
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
			</el-upload>
		</el-dialog>
	</div>
</template>

<script>
	import {
		// getImagesSource,
		getImitateImagesSource,
		updateCollect,
		deleteImage
	} from '@/api/image.js'
	export default {
		data () {
			const token = window.sessionStorage.getItem('token')
			return {
				// 查询信息数据对象
				queryInfo: {
					collect: false,
					page: 1,
					per_page: 10
				},
				total: 50,
				// 图片素材
				imagesSource: [],
				// 上传素材对话框显示与隐藏
				uploadDialogVisible: false,
				// 文件上传请求头
				uploadHeaders: {
					Authorization: `Bearer ${token}`
				},
				// 选中的下标
				selected: null
			}
		},
		props: {
			// 显示添加素材按钮
			isShowAdd: {
				type: Boolean,
				default: false
			},
			// 显示素材选项
			isShowOption: {
				type: Boolean,
				default: false
			},
			// 显示选中图标
			isShowSelected: {
				type: Boolean,
				default: false
			}
		},
		created () {
			this._loadImagesSource()
		},
		methods: {
			// 加载图片素材
			_loadImagesSource () {
				/*
				 *
				 *  //失效的接口
				 *	getImagesSource(this.queryInfo).then(({data:res}) => {
				 *		this.imagesSource = res.data.results
				 *  }).catch(err => {
				 *		this.$message.error('获取图片素材失败:' + err)
				 *  })
				 *
				 */

				// 本地模拟数据
				getImitateImagesSource(this.queryInfo).then(({
					data: res
				}) => {
					res.forEach(item => {
						this.$set(item, 'option', false)
					})
					this.imagesSource = res
				}).catch(err => {
					this.$message.error('获取图片素材失败' + err)
				})
			},
			// 分页器页码发生改变事件
			handleCurrentChange (newPage) {
				this.queryInfo.page = newPage
				// 调用函数
				this._loadImagesSource()
			},
			// 全部/收藏切换
			collectChanged () {
				// 重置为默认显示第一页
				this.queryInfo.page = 1
				this._loadImagesSource()
			},
			// 文件上传成功的钩子函数
			uploadSuccess () {
				this.uploadDialogVisible = false
				this._loadImagesSource()
			},
			// 文件上传失败的钩子函数
			uploadError () {
				this.$message.error('上传素材失败！')
			},
			// 收藏/取消收藏素材
			updateCollect (img) {
				// 打开加载
				img.option = true
				updateCollect(img.id, !img.is_collected).then(res => {
					this.$message.success('更新成功！')
					this._loadImagesSource()
					// 关闭加载
					img.option = false
				}).catch(err => {
					this.$message.error('更新失败:' + err)
					// 关闭加载
					img.option = false
				})
			},
			// 删除图片
			async _deleteImage (img) {
				// 提示是否删除
				const confirmResult = await this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
				// 判断是否要删除
				if (confirmResult !== 'confirm') return this.$message.info('你点击了取消按钮！')

				img.option = true
				deleteImage(img.id).then((res) => {
					this.$message.success('删除图片成功！')
					this._loadImagesSource()
					img.option = false
				}).catch(err => {
					this.$message.error('删除图片失败：' + err)
					img.option = false
				})
			}
		}
	}
</script>

<style scoped lang="less">
	.screend {
		margin-bottom: 20px;
	}

	.img-box {
		margin-bottom: 15px;
		position: relative;

		.el-image {
			height: 150px;
		}

		.img-option {
			position: absolute;
			width: 100%;
			height: 30px;
			left: 0;
			bottom: 1px;
			background: rgba(0, 0, 0, .4);
			display: flex;
			align-items: center;
			justify-content: center;
			.collect-btn {
				border: 0;
				color: #fff;
				font-size: 16px;
				background: transparent;
				&::before {
					background-color: transparent;
				}
				&.on {
					color: red;
				}
			}
		}

		.selected{
			position: absolute;
			z-index: 1;
			width: 100%;
			height: 150px;
			top: 0;
			left: 0;
			background: rgba(18, 18, 18, 0.5);
			&::before{
				content: '';
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background: url(../assets/images/selected.png) no-repeat;
				background-size: 80px;
				background-position: 50% 50%;
			}
		}
	}
</style>
